package at.fhj.itm;

/**
 * An implementation of a queue
 * 
 * @author Daniel Geymayer
 * @version 1.0
 * 
 */
public class Queue {

	/** The maximum amount of elements which can be stored in the queue */
	private int maxSize;

	/** The queue stored as an array */
	private long[] queArray;

	/** The element at the front of the queue */
	private int front;

	/** The element at the rear of the queue */
	private int rear;

	/** The amount of elements in the queue */
	private int nItems;

	/**
	 * Constructor for initializing the queue
	 * 
	 * @param s The maximum size of the queue
	 */
	public Queue(int s) {
		maxSize = s;
		queArray = new long[maxSize];
		front = 0;
		rear = -1;
		nItems = 0;
	}

	/**
	 * Puts an item at the end of a queue
	 * 
	 * @param j Element to be inserted
	 */
	public void insert(long j) {
		if (rear == maxSize - 1) // deal with wraparound
			rear = -1;
		queArray[++rear] = j; // increment rear and insert
		nItems++;
	}

	/**
	 * Take item from front of queue
	 *
	 * @return Returns the removed element
	 */
	public long remove() {
		long temp = queArray[front++]; // get value and incr front
		if (front == maxSize) // deal with wraparound
			front = 0;
		nItems--; // one less item
		return temp;
	}

	/**
	 * Gives the item at the front
	 * 
	 * @return Returns the front item
	 */
	public long peekFront() {
		return queArray[front];
	}

	/**
	 * Checks whether the queue is empty or not
	 * 
	 * @return Returns true if the queue is empty and false if there is at least one item in the queue
	 */
	public boolean isEmpty() {
		return (nItems == 0);
	}

	/**
	 * Checks whether the maximum size of the queue has been reached
	 * 
	 * @return Returns true if amounts of elements is equal to the maximum size of the queue
	 */
	public boolean isFull() {
		return (nItems == maxSize);
	}

	/**
	 * Gives the size of the queue
	 * 
	 * @return Returns the size of the queue
	 */
	public int size() {
		return nItems;
	}

	/**
	 * main method
	 * 
	 * @param args Arguments taken
	 */
	public static void main(String[] args) {
		Queue theQueue = new Queue(5);

		theQueue.insert(10);
		theQueue.insert(20);
		theQueue.insert(30);
		theQueue.insert(40);

		theQueue.remove();
		theQueue.remove();
		theQueue.remove();

		theQueue.insert(50);
		theQueue.insert(60); // (wraps around)
		theQueue.insert(70);
		theQueue.insert(80);

		while (!theQueue.isEmpty()) {
			long n = theQueue.remove(); // (40, 50, 60, 70, 80)
			System.out.print(n);
			System.out.print(" ");
		}
		System.out.println("");
	}
}
